from flask import Flask, jsonify, request
from flask_cors import CORS
import requests
import os
import json
import time
from datetime import datetime, timedelta

app = Flask(__name__)
CORS(app)

# 配置 - 直接使用API密钥
DEEPSEEK_API_KEY = 'sk-96b10925c71c4fc8b813ab15e8b792d1'
DEEPSEEK_API_URL = 'https://api.deepseek.com/v1/chat/completions'

# 简单的内存缓存
quote_cache = {
    'quote': '',
    'timestamp': None,
    'cache_duration': 21600  # 6小时缓存，减少API调用频率
}

# 备用语录库
FALLBACK_QUOTES = [
    "每一天都是新的开始，充满无限可能。",
    "相信自己，你比想象中更强大。",
    "成功不是终点，失败不是末日，继续前进的勇气才最可贵。",
    "今天的努力是明天成功的基石。",
    "保持积极的心态，世界会因你而更美好。"
]

def is_cache_valid():
    """检查缓存是否有效"""
    if not quote_cache['timestamp']:
        return False
    
    cache_time = quote_cache['timestamp']
    current_time = datetime.now()
    return (current_time - cache_time).seconds < quote_cache['cache_duration']

def get_quote_from_deepseek():
    """从 DeepSeek API 获取语录"""
    # if not DEEPSEEK_API_KEY:
    #     return None
    
    headers = {
        'Authorization': f'Bearer sk-96b10925c71c4fc8b813ab15e8b792d1',
        'Content-Type': 'application/json'
    }
    
    payload = {
        'model': 'deepseek-chat',
        'messages': [
            {
                'role': 'user',
                'content': '请生成一句积极正面的励志语录，要求简洁有力，不超过30个字，适合作为每日激励。'
            }
        ],
        'max_tokens': 100,
        'temperature': 0.8
    }
    
    try:
        response = requests.post(DEEPSEEK_API_URL, headers=headers, json=payload, timeout=10)
        response.raise_for_status()
        
        data = response.json()
        quote = data['choices'][0]['message']['content'].strip()
        
        # 简单的内容过滤
        if len(quote) > 50 or any(word in quote.lower() for word in ['负面', '失败', '痛苦']):
            return None
            
        return quote
        
    except Exception as e:
        print(f"DeepSeek API 调用失败: {e}")
        return None

@app.route('/api/quote', methods=['GET'])
def get_quote():
    """获取语录接口"""
    try:
        # 检查缓存
        if is_cache_valid() and quote_cache['quote']:
            return jsonify({
                'success': True,
                'quote': quote_cache['quote'],
                'source': 'cache'
            })
        
        # 尝试从 DeepSeek API 获取
        quote = get_quote_from_deepseek()
        
        if quote:
            # 更新缓存
            quote_cache['quote'] = quote
            quote_cache['timestamp'] = datetime.now()
            
            return jsonify({
                'success': True,
                'quote': quote,
                'source': 'deepseek'
            })
        else:
            # 使用备用语录
            import random
            fallback_quote = random.choice(FALLBACK_QUOTES)
            
            return jsonify({
                'success': True,
                'quote': fallback_quote,
                'source': 'fallback'
            })
            
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/health', methods=['GET'])
def health_check():
    """健康检查接口"""
    return jsonify({
        'status': 'healthy',
        'timestamp': datetime.now().isoformat()
    })

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)